/*
 * Copyright (C) 2008 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.lzx.iteam.dimensioncode.result;

import android.app.Activity;
import android.content.Intent;
import android.telephony.PhoneNumberUtils;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.StyleSpan;
import com.google.zxing.client.result.AddressBookParsedResult;
import com.google.zxing.client.result.ParsedResult;
import com.lzx.iteam.ResultActivity;
import com.lzx.iteam.util.StringUtil;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Handles address book entries.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
public final class AddressBookResultHandler extends ResultHandler {

  private static final DateFormat[] DATE_FORMATS = {
    new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH),
    new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH),
    new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH),
    new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH),
  };
  static {
    for (DateFormat format : DATE_FORMATS) {
      format.setLenient(false);
    }
  }


    /**
     *  得到 扫描后的数据 并传出去
     * @param activity
     * @param result
     * @param data
     * @param filePath
     * @param groupId
     * @param cloudMode
     */
    public AddressBookResultHandler(Activity activity, ParsedResult result, AddressBookParsedResult data, byte[] filePath, String groupId, boolean cloudMode) {
        super(activity, result);
        AddressBookParsedResult addressResult;
        if(data == null){
            addressResult = (AddressBookParsedResult) result;
        }else{
            addressResult = data;
        }

        String[] addresses = addressResult.getAddresses();
        String[] addressType = addressResult.getAddressTypes();
        String[] phoneNumbers = addressResult.getPhoneNumbers();
        String[] emails = addressResult.getEmails();
        String[] displayName = addressResult.getNames();
        displayName = formatName(displayName);
        String[] phoneTypes = addressResult.getPhoneTypes();
        String[] emailTypes = addressResult.getEmailTypes();
        String url = addressResult.getURLs() != null ? addressResult.getURLs()[0] : null;
        String org = addressResult.getOrg();
        String notes = addressResult.getNote();
        String jobTitle = addressResult.getTitle();
        Intent addContact = new Intent(activity, ResultActivity.class);

//        Intent insert = new Intent(Constants.INSERT_CONTACT_ACTION, Contacts.CONTENT_URI);
        //phone numbers
        /*if(null != phoneNumbers && phoneNumbers.length > 0){
            for(int i = 0; i<phoneNumbers.length; i++){
                if(!StringUtil.isEmpty(phoneNumbers[i])){
//                    insert.putExtra(Contents.PHONE_KEYS[i], phoneNumbers[i]);
                    addContact.putExtra("phone",phoneNumbers[i]);
                }
            }    
        }*/

        addContact.putExtra("phone",phoneNumbers[0]);
        /*if (phoneNumbers.length>1){
            addContact.putExtra("landline",phoneNumbers[1]);
        }else{
            addContact.putExtra("landline","");
        }*/


        
       /* //phone type
        if(null != phoneTypes && phoneTypes.length > 0){
            for(int i = 0; i<phoneTypes.length; i++){
                if(!StringUtil.isEmpty(phoneTypes[i])){
                    insert.putExtra(Contents.PHONE_TYPE_KEYS[i], phoneTypes[i]);
                }
            }
        }*/
        
        //email
        if(null != emails && emails.length > 0){
            for(int i = 0; i < emails.length; i++){
                if(!StringUtil.isEmpty(emails[i])){
//                    insert.putExtra(Contents.EMAIL_KEYS[i], emails[i]);
                    addContact.putExtra("email",emails[i]);
                }
            }
        }else{
            addContact.putExtra("email","");
        }
        
        /*//email type
        if(null!= emailTypes && emailTypes.length > 0){
            for(int i = 0; i < emailTypes.length; i++){
                if(!StringUtil.isEmpty(emailTypes[i])){
                    insert.putExtra(Contents.EMAIL_TYPE_KEYS[i], emailTypes[i]);
                }
            }
        }*/
        
//        insert.putExtra(Insert.COMPANY, org);
//        insert.putExtra(Insert.JOB_TITLE, jobTitle);
        addContact.putExtra("company",org);
        addContact.putExtra("job",jobTitle);
//        addContact.putExtra("note",notes);

        if(addresses != null && addresses.length > 0){
            if(!StringUtil.isEmpty(addresses[0])){
//                insert.putExtra(Insert.POSTAL, addresses[0]);
                addContact.putExtra("address",addresses[0]);
            }
        }else{
            addContact.putExtra("address","");
        }
        /*if(addressType != null && addressType.length > 0){
            if(!StringUtil.isEmpty(addressType[0])){
                insert.putExtra(Insert.POSTAL_TYPE, addressType[0]);
            }
        }
        insert.putExtra(Insert.NOTES, notes);
        // url 需要在编辑页面接收
        insert.putExtra(Website.URL, url);*/

        if(displayName != null && displayName.length > 0){
//            insert.putExtra(Insert.NAME, displayName[0]);
            addContact.putExtra("name",displayName[0]);
        }

        /*if(filePath != null && filePath.length > 0){
            insert.putExtra(Constants.INSERT_PHOTO, filePath);
        }
        if(!StringUtil.isEmpty(groupId)){
            insert.putExtra("group_id", groupId);
            insert.putExtra("cloud_mode", cloudMode);
        }

        activity.startActivityForResult(insert, Constants.CLOSE_CAPTURE);*/
//        activity.startActivityForResult(addContact, Constants.CLOSE_CAPTURE);
        activity.startActivity(addContact);
        activity.finish();
    }

  private static Date parseDate(String s) {
    for (DateFormat currentFormat : DATE_FORMATS) {
      try {
        return currentFormat.parse(s);
      } catch (ParseException e) {
        // continue
      }
    }
    return null;
  }
  
    private String[] formatName(String[] name) {
        if (name == null) return new String[] {""};

        String displayName = name[0];
        if(!StringUtil.isEmpty(displayName)){
            String[] format = displayName.split(" ");
            String[] formatedName = new String[1];
            if (format.length == 2) {
                formatedName[0] = format[1] + " " + format[0];
                return formatedName;
            }
        }
        return name;

    }

  // Overriden so we can hyphenate phone numbers, format birthdays, and bold the name.
  @Override
  public CharSequence getDisplayContents() {
    AddressBookParsedResult result = (AddressBookParsedResult) getResult();
    StringBuilder contents = new StringBuilder(100);
    ParsedResult.maybeAppend(result.getNames(), contents);
    int namesLength = contents.length();

    String pronunciation = result.getPronunciation();
    if (pronunciation != null && pronunciation.length() > 0) {
      contents.append("\n(");
      contents.append(pronunciation);
      contents.append(')');
    }

    ParsedResult.maybeAppend(result.getTitle(), contents);
    ParsedResult.maybeAppend(result.getOrg(), contents);
    ParsedResult.maybeAppend(result.getAddresses(), contents);
    String[] numbers = result.getPhoneNumbers();
    if (numbers != null) {
      for (String number : numbers) {
        ParsedResult.maybeAppend(PhoneNumberUtils.formatNumber(number), contents);
      }
    }
    ParsedResult.maybeAppend(result.getEmails(), contents);
    ParsedResult.maybeAppend(result.getURLs(), contents);

    String birthday = result.getBirthday();
    if (birthday != null && birthday.length() > 0) {
      Date date = parseDate(birthday);
      if (date != null) {
        ParsedResult.maybeAppend(DateFormat.getDateInstance(DateFormat.MEDIUM).format(date.getTime()), contents);
      }
    }
    ParsedResult.maybeAppend(result.getNote(), contents);

    if (namesLength > 0) {
      // Bold the full name to make it stand out a bit.
      Spannable styled = new SpannableString(contents.toString());
      styled.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, namesLength, 0);
      return styled;
    } else {
      return contents.toString();
    }
  }

}
